<?php
class DB
{
	/*
	#DB
	addActivity($session,$userid,$ip,$url,$time)	REPLACE TBL_ACTIVITY '$session','$userid','$ip','$url','$time'
	removeActivity($session)				"DELETE FROM ".TBL_ACTIVITY." WHERE session = '$session'
	removeInactiveUsers()					"DELETE FROM ".TBL_ACTIVITY." WHERE time < $timeout"
	getUserID($email)						"SELECT userid FROM ".TBL_USERS." WHERE epost = '$email'"
	checkUserID($email,$userid)				"SELECT userid FROM ".TBL_USERS." WHERE epost = '$email'";		 !!!!skrivas om!!!!
	checkEmailPass($email,$pass)			"SELECT pass FROM ".TBL_USERS." WHERE epost = '$email'"; compare $pass
	email_taken($email)						"SELECT epost FROM ".TBL_USERS." WHERE epost = '$email'";
	updateUserField($email, $field, $value)	"UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE epost = '$email'";
	get_user_info($email)					"SELECT * FROM ".TBL_USERS." WHERE epost = '$email'";
	get_user_adress_info($adress_id			"SELECT * FROM ".TBL_ADRESS." WHERE adress_id = '$adress_id'";
	getNumMembers()							count TBL_USERS
	calcNumActiveUsers()					db->count TBL_USER uid !0
	calcNumActiveGuests()					db->count TBL_USER uid 0
	mysql_get_array($query)					mysql_fetch_array -> return array
	mysql_get_row($query)
	query($query)
	(!!!!num rows!!!))
	*/
   var $connection;         //The MySQL database connection
   var $num_active_users;   //Number of active users viewing site
   var $num_active_guests;  //Number of active guests viewing site
   var $num_members;        //Number of signed-up users
   /* Note: call getNumMembers() to access $num_members! */

	function DB(){
      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
      mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
      
      /**
       * Only query database to find out number of members
       * when getNumMembers() is called for the first time,
       * until then, default value set.
       */
      $this->num_members = -1;
		
      if(TRACK_VISITORS){
         /* Calculate number of users at site 
         $this->calcNumActiveUsers();*/
      
         /* Calculate number of guests at site 
         $this->calcNumActiveGuests();*/
      }
   }
	
	
   function addLogg($session,$userid,$ip,$url,$do,$referer,$time){
      /*$q = "UPDATE ".TBL_USERS." SET timestamp = '$time' WHERE username = '$username'";
      mysql_query($q, $this->connection);*/
      
      if(!TRACK_VISITORS) return;
      $q = "INSERT INTO ".TBL_LOG." VALUES ('$session','$userid','$ip','$url','$do','$referer','$time')";
      mysql_query($q, $this->connection) or die(mysql_error());
      $this->calcNumActiveUsers();
   }	
	
	
	
   /**
    * addActiveUser - Updates username's last active timestamp
    * in the database, and also adds him to the table of
    * active users, or updates timestamp if already there.
    */
   function addActivity($session,$userid,$ip,$url,$time){
      /*$q = "UPDATE ".TBL_USERS." SET timestamp = '$time' WHERE username = '$username'";
      mysql_query($q, $this->connection);*/
      
      if(!TRACK_VISITORS) return;
      $q = "REPLACE INTO ".TBL_ACTIVITY." VALUES ('$session','$userid','$ip','$url','$time')";
      mysql_query($q, $this->connection) or die(mysql_error());
      $this->calcNumActiveUsers();
   }

   /* removeActiveUser */
   function removeActivity($session){
      if(!TRACK_VISITORS) return;
      $q = "DELETE FROM ".TBL_ACTIVITY." WHERE session = '$session'";
      mysql_query($q, $this->connection) or die(mysql_error());
      $this->calcNumActiveUsers();
   }

   /* removeInactiveUsers */
   function removeInactiveUsers(){
      if(!TRACK_VISITORS) return;
      $timeout = time()-USER_TIMEOUT*60;
      $q = "DELETE FROM ".TBL_ACTIVITY." WHERE time < $timeout";
      mysql_query($q, $this->connection);
      $this->calcNumActiveUsers();
   }
   
	function getUserID($email){
      if(!get_magic_quotes_gpc()) {
			$email = addslashes($email);
      }

      /* Verify that user is in database */
      $q = "SELECT userid FROM ".TBL_USERS." WHERE epost = '$email'";
      $result = $this->query($q);
      if(!$result || (mysql_numrows($result) < 1)){
         return -1; // epostadressen finns inte i DB
      }

      /* hämta user_id från DB */
      $dbarray = mysql_fetch_array($result);
      $dbarray['userid'] = stripslashes($dbarray['userid']);
      $userid = stripslashes($dbarray['userid']);

		return $userid;
	}
	function checkUserID($email,$userid){
      /* Add slashes if necessary (for query) */
      if(!get_magic_quotes_gpc()) {
			$email = addslashes($email);
      }

      /* Verify that user is in database */
      $q = "SELECT userid FROM ".TBL_USERS." WHERE epost = '$email'";
      $result = $this->query($q);
      if(!$result || (mysql_numrows($result) < 1)){
         return 1; // epostadressen finns inte i DB
      }

      /* hämta user_id från DB */
      $dbarray = mysql_fetch_array($result);
      $dbarray['userid'] = stripslashes($dbarray['userid']);
      $userid = stripslashes($userid);

      /* Validate that userid is correct */
      if($userid == $dbarray['userid']){
         return 0; //Success! Username and userid confirmed
      }
      else{
         return 2; //Indicates userid invalid
      }
	}

	function checkEmailPass($email,$pass){
      if(!get_magic_quotes_gpc()) {
			$email = addslashes($email);
      }
		
      $q = "SELECT pass FROM ".TBL_USERS." WHERE epost = '$email'";
      $result = $this->query($q);
      if(!$result || (mysql_numrows($result) < 1)){
         return 1; // epostadressen finns inte i DB
      }

      /* hämta lösenordet från DB */
      $dbarray = mysql_fetch_array($result);
      $dbarray['pass'] = stripslashes($dbarray['pass']);
      $pass = stripslashes($pass);

      /* kontrollera att pass stämmer */
      if($pass == $dbarray['pass']){
         return 0; // lösenord och email stämmer
      }
      else{
         return 2; // lösenord fel så return 2
      }
	}


	/* registrera funktioner */
   function email_taken($email){
      if(!get_magic_quotes_gpc()){
         $email = addslashes($email);
      }
      $q = "SELECT epost FROM ".TBL_USERS." WHERE epost = '$email'";
      $result = $this->query($q);
      return (mysql_numrows($result));
   }

   function updateUserField($email, $field, $value){
      $q = "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE epost = '$email'";
      return mysql_query($q, $this->connection);
   }

   function get_user_info($email){
      $q = "SELECT * FROM ".TBL_USERS." WHERE epost = '$email'";
      $result = mysql_query($q, $this->connection);
      /* Error occurred, return given name by default */
      if(!$result || (mysql_numrows($result) < 1)){
         return NULL;
      }
      /* Return result array */
      $dbarray = mysql_fetch_array($result);
      return $dbarray;
   }
   function get_user_adress_info($adress_id){
      $q = "SELECT * FROM ".TBL_ADRESS." WHERE adress_id = '$adress_id'";
      $result = mysql_query($q, $this->connection);
      /* Error occurred, return given name by default */
      if(!$result || (mysql_numrows($result) < 1)){
         return NULL;
      }
      /* Return result array */
      $dbarray = mysql_fetch_array($result);
      return $dbarray;
   }


	
   /**
    * getNumMembers - Returns the number of signed-up users
    * of the website, banned members not included. The first
    * time the function is called on page load, the database
    * is queried, on subsequent calls, the stored result
    * is returned. This is to improve efficiency, effectively
    * not querying the database when no call is made.
    */
   function getNumMembers(){
      if($this->num_members < 0){
         $q = "SELECT count(*) FROM ".TBL_USERS;
         $result = $this->query($q);
         $this->num_members = mysql_numrows($result);
      }
      return $this->num_members;
   }
   
   /**
    * calcNumActiveUsers - Finds out how many active users
    * are viewing site and sets class variable accordingly.
    */
   function calcNumActiveUsers(){
      /* Calculate number of users at site */
      $q = "SELECT count(*) FROM ".TBL_ACTIVITY." WHERE userid != 0";
      $result = mysql_query($q, $this->connection);
      $this->num_active_users = mysql_numrows($result);
   }
   
   /**
    * calcNumActiveGuests - Finds out how many active guests
    * are viewing site and sets class variable accordingly.
    */
   function calcNumActiveGuests(){
      /* Calculate number of guests at site */
      $q = "SELECT count(*) FROM ".TBL_ACTIVITY." WHERE userid == 0";
      $result = mysql_query($q, $this->connection);
      $this->num_active_guests = mysql_numrows($result);
   }
   function mysql_get_array($query){
		$result = $this->query($query);
		$array = Array();
		if($result){
			while ( $row = mysql_fetch_array($result) )
			{
				$array[] = $row;
			}
		}
		return $array;	
	}
	function mysql_get_row($query){
		$result = $this->query($query);
		$row = mysql_fetch_row($result);
		return $row;

	}
   /**
    * query - Performs the given query on the database and
    * returns the result, which may be false, true or a
    * resource identifier.
    */
   function query($query){
      return mysql_query($query, $this->connection);
   }

}
?>